﻿// Copyright © 2011 Paul Vanukoff (pvanukoff@gmail.com)

using System;
using Bravura.Contracts.PluginTypes;
using Bravura.Core.PluginLib;
using Bravura.Native.PluginBase;

namespace Bravura.Native.Plugins.Filters
{
	/// <summary>
	/// A non-linear distortion, using the Math.Pow() function.
	/// </summary>
	public class Distortion : Filter, IFilter
	{
		#region Fields

		private double _zero = 0.00;
		private double _power = 0.90;

		#endregion

		#region Properties

		public double Zero
		{
			get { return _zero; }
			set { _zero = value; }
		}

		public double Power
		{
			get { return _power; }
			set { _power = value; }
		}

		#endregion

		public Distortion(IAudioPluginHost host, int sampleRate) : base(host, sampleRate)
		{
		}

		#region Open / Process / Close

		public override void Open()
		{
		}

		public override void Process(int count)
		{
			// read input buffer
			double[] ioBuff = GetInputBuffer(0).Read(count);

			// process
			for (int i = 0; i < count; i++)
			{
				double o = ioBuff[i];
				double v = o;
				v = v - _zero;
				v = (v < 0.0) ? -Math.Pow(-v, _power) : Math.Pow(v, _power);
				v = v + _zero;
				ioBuff[i] = _wetMix * v + _dryMix * o;
			}

			// write to output buffer
			GetOutputBuffer(0).Write(ioBuff, count);
		}

		public override void Close()
		{
		}

		#endregion
	}
}
